﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using UCenter.Core.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers;

namespace UCenter.SQLServerProvider
{
    //[ExceptionCallHandler("Data Access Exception Policy")]
    public abstract class RepositoryBase
    {
        #region Constructors

        protected RepositoryBase()
            : this(DefaultConnectionString, true)
        {
        }

        protected RepositoryBase(string fileOrServerOrConnection, bool isReadOnly)
            : this(new RepositoryContext(fileOrServerOrConnection, isReadOnly))
        {
        }

        protected RepositoryBase(IDbConnection connection, bool isReadOnly)
            : this(new RepositoryContext(connection, isReadOnly))
        {
        }

        protected RepositoryBase(RepositoryContext context)
        {
            DataContext = context;
        }

        #endregion

        #region Properties

        private RepositoryContext DataContext { get; set; }

        protected IRepositoryContext Context
        {
            get
            {
                return DataContext;
            }
        }

        public bool IsReadOnly
        {
            get { return Context.IsReadOnly; }
            set { DataContext.ResetContext(value); }
        }

        #endregion

        #region Static Properties

        protected static string GetRepositoryConnectionName()
        {
            string repositoryConnectionName = ConfigurationManager.AppSettings["RepositoryConnectionName"];
            if (string.IsNullOrEmpty(repositoryConnectionName))
            {
                throw new InvalidOperationException("The applicationsetting key 'RepositoryConnectionName' is not set.");
            }
            return repositoryConnectionName;
        }

        protected static string DefaultConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings[GetRepositoryConnectionName()].ConnectionString;
            }
        }
        #endregion

    }
}
